package controller

import (
	"gf-start-kit/app/middleware"
	"gf-start-kit/library/base"
	"gf-start-kit/library/resp"
	"gf-start-kit/library/router"
	"gf-start-kit/plugins/job/lib/jcron"
	"gf-start-kit/plugins/job/service"
	"github.com/gogf/gf/net/ghttp"
)

type JobController struct {
	base.Controller
	service *service.JobService
}

func init() {
	ctl := new(JobController)
	router.New("job", "system/job", middleware.Auth).
		POST("/save", ctl.Save, router.Opts{
			OpenAuth: true,
		}).
		POST("/edit", ctl.Edit, router.Opts{
			OpenAuth: true,
		}).
		POST("/remove", ctl.Remove, router.Opts{
			OpenAuth: true,
		}).
		GET("/get", ctl.Get).
		GET("/getTaskLists", ctl.GetTaskLists).
		GET("/page", ctl.Page).
		POST("/start", ctl.JobStart, router.Opts{
			OpenAuth: true,
		}).
		POST("/stop", ctl.JobStop, router.Opts{
			OpenAuth: true,
		})
}

func (a *JobController) Save(r *ghttp.Request) {
	var req service.AddReq
	if err := r.Parse(&req); err != nil {
		resp.Error(r).SetError(err).Json()
	}
	_, err := a.service.Save(req)
	if err != nil {
		resp.Error(r).SetError(err).Json()
	}
	resp.Success(r).Json()
}
func (a *JobController) Edit(r *ghttp.Request) {
	var req service.EditReq
	if err := r.Parse(&req); err != nil {
		resp.Error(r).SetError(err).Json()
	}
	_, err := a.service.Update(req)
	if err != nil {
		resp.Error(r).SetError(err).Json()
	}
	resp.Success(r).Json()
}

//分页列表
func (a *JobController) Page(r *ghttp.Request) {
	form := base.NewForm(r.GetQueryMap())
	list, err := a.service.Page(&form)
	if err != nil {
		resp.Error(r).SetError(err).Json()
	}
	resp.Success(r).SetData(resp.ListsData{Total: form.Total, Rows: list}).Json()
}
func (a *JobController) Remove(r *ghttp.Request) {
	id := r.GetInt64("id")
	_, err := a.service.Remove(id)
	if err != nil {
		resp.Error(r).SetError(err).Json()
	}
	resp.Success(r).Json()
}
func (a *JobController) Get(r *ghttp.Request) {
	id := r.GetInt64("id")
	one, err := a.service.Get(id)
	if err != nil {
		resp.Error(r).SetError(err).Json()
	}
	resp.Success(r).SetData(one).Json()
}
func (a *JobController) GetTaskLists(r *ghttp.Request) {
	lists := jcron.Map()
	resp.Success(r).SetData(lists).Json()
}
func (a *JobController) JobStart(r *ghttp.Request) {
	id := r.GetInt64("id")
	if err := a.service.Start(id); err != nil {
		resp.Error(r).Json()
	}
	resp.Success(r).Json()
}
func (a *JobController) JobStop(r *ghttp.Request) {
	id := r.GetInt64("id")
	_ = a.service.Stop(id)
	resp.Success(r).Json()
}
